package com.baofengtv.wake;

import android.app.KeyguardManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class MyService extends Service {

    //声明键盘管理器
    KeyguardManager mKeyguardManager = null;
    //声明键盘锁
    private KeyguardManager.KeyguardLock mKeyguardLock = null;
    //声明电源管理器
    private PowerManager pm;
    private PowerManager.WakeLock wakeLock;

    private static int rand = 45;

    public MyService() {
    }
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");

                Date curDate = new Date(System.currentTimeMillis());
                String[] dd = formatter.format(curDate).split(":");
                formatter = new SimpleDateFormat("EEEE");
                String week = formatter.format(curDate);
                String hh = dd[0];
                String mm = dd[1];
                Log.d("czx","week="+week+ "h="+hh+" m="+mm);
                if(week.equals("星期日")||week.equals("星期六")) return;

                if(hh.equals("20")){//每天晚上8天更新第二天上午打开应用的时间，每天更新60次{捂脸}
                    Random random = new Random();
                    int t = random.nextInt(19);
                    rand = (45+t)%60;//为 （45~64）%60==（0~4||45~59）
                    Log.d("czx","rand=="+rand);
                }
                if(rand>=45){
                    if(!hh.equals("09")||Integer.valueOf(mm)<rand) return;
                }
                if(rand<5){
                    if(!hh.equals("10")||Integer.valueOf(mm)>10)//10:mm-10:10都会打开。
                        return;
                }
//                if(!hh.equals("09")||Integer.valueOf(mm)<rand) {
//                    return;
//                }
                startService(new Intent(context,MyService.class));



            }

        }
    };
    @Override
    public void onCreate() {
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_TIME_TICK);
        registerReceiver(receiver,intentFilter);
        //获取电源的服务
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        //获取系统服务
        mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("czx","onStart");
//       // if(wakeLock==null||!wakeLock.isHeld()){
            wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
//
//        }
        wakeLock.acquire();
        Log.i("Log : ", "------>mKeyguardLock");
        //初始化键盘锁，可以锁定或解开键盘锁
        mKeyguardLock = mKeyguardManager.newKeyguardLock("");
        //禁用显示键盘锁定
        mKeyguardLock.disableKeyguard();
        startDD();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                if(wakeLock!=null&&wakeLock.isHeld())
//                    wakeLock.release();
//            }
//        },10*60*1000);
        wakeLock.release();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if(wakeLock!=null&&wakeLock.isHeld())
            wakeLock.release();
        unregisterReceiver(receiver);
        super.onDestroy();
        Log.d("czx","onDestroy");
        startService(new Intent(getApplicationContext(),MyService.class));
    }
    private void startDD(){
        String packageName = "com.alibaba.android.rimet";
        PackageInfo packageInfo = null;
        try {
             packageInfo = getPackageManager().getPackageInfo(packageName,0);

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if(packageInfo==null) return;
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageInfo.packageName);
// 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if(resolveinfo== null) return;
        Log.d("czx","activity name = "+resolveinfo.activityInfo.name);
        ComponentName componentName = new ComponentName(packageName,resolveinfo.activityInfo.name);
        Intent intent1 = new Intent();
        intent1.setComponent(componentName);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent1);

    }

    Handler handler  = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
}
